<?php

namespace app\company\controller;

use app\admin\model\department\Lists;
use app\admin\model\device\Info;
use app\admin\model\money\Change;
use app\admin\model\month\Salary;
use app\admin\model\product\Order;
use app\admin\model\profile\Cost;
use app\admin\model\Suggest;
use app\admin\model\user\Finance;
use app\admin\model\user\Sign;
use app\admin\model\user\Statics;
use app\common\controller\CompanyApi;
use app\common\library\Ems;
use app\common\library\Sms;
use fast\Random;
use think\Config;
use think\Db;
use think\Validate;

/**
 * 会员接口
 */
class User extends CompanyApi
{
    protected $noNeedLogin = ['login', 'mobilelogin', 'register', 'resetpwd', 'changeemail', 'changemobile', 'third'];
    protected $noNeedRight = '*';

    public function _initialize()
    {
        parent::_initialize();

        if (!Config::get('fastadmin.usercenter')) {
            $this->error(__('User center already closed'));
        }

    }

    /**
     * 会员中心
     */
    public function index()
    {
        $uinfo = $this->auth->getUser();

//        $department_name = '';
//        if ($uinfo['is_manager'] == 0) {
            $department_name = \app\admin\model\department\Lists::where('id', $uinfo['department_id'])->value('name');
//        }

        $data = [
            "id" => $uinfo['id'],
            "username" => $uinfo['username'],
            "nickname" => $uinfo['nickname'],
            "mobile" => $uinfo['mobile'],
            "avatar" => make_full_url($uinfo['avatar']),
            "createtime" => $uinfo['createtime'],
            "updatetime" => $uinfo['updatetime'],
            "department_name" => $department_name,
            'is_leader' => $uinfo['is_leader'],
            'is_manager' => $uinfo['is_manager']
        ];
        $this->success('', $data);
    }

    /**
     * 会员登录
     *
     * @ApiMethod (POST)
     * @param string $account 账号
     * @param string $password 密码
     */
    public function login()
    {
        $account = $this->request->post('account');
        $password = $this->request->post('password');
        if (!$account || !$password) {
            $this->error(__('Invalid parameters'));
        }
        $ret = $this->auth->login($account, $password);
        if ($ret) {
            $data = ['userinfo' => $this->auth->getUserinfo()];
            $this->success(__('Logged in successful'), $data);
        } else {
            $this->error($this->auth->getError());
        }
    }

    /**
     * 手机验证码登录
     *
     * @ApiMethod (POST)
     * @param string $mobile 手机号
     * @param string $captcha 验证码
     */
    public function mobilelogin()
    {
        $mobile = $this->request->post('mobile');
        $captcha = $this->request->post('captcha');
        if (!$mobile || !$captcha) {
            $this->error(__('Invalid parameters'));
        }
        if (!Validate::regex($mobile, "^1\d{10}$")) {
            $this->error(__('Mobile is incorrect'));
        }
        if (!Sms::check($mobile, $captcha, 'mobilelogin')) {
            $this->error(__('Captcha is incorrect'));
        }

        $user = \app\common\model\User::getByMobile($mobile);
        if (!$user) {
            $this->error('该用户尚未注册！');
//        } else {
//            $ret = $this->auth->register($mobile, Random::alnum(), '', $mobile, []);
        }

        if ($user->status != 'normal') {
            $this->error(__('Account is locked'));
        }
        //如果已经有账号则直接登录
        $ret = $this->auth->direct($user->id);
        if ($ret) {
            Sms::flush($mobile, 'mobilelogin');
            $data = ['userinfo' => $this->auth->getUserinfo()];
            $this->success(__('Logged in successful'), $data);
        } else {
            $this->error($this->auth->getError());
        }
    }

    /**
     * 退出登录
     * @ApiMethod (POST)
     */
    public function logout()
    {
        if (!$this->request->isPost()) {
            $this->error(__('Invalid parameters'));
        }
        $this->auth->logout();
        $this->success(__('Logout successful'));
    }

    /**
     * 修改会员个人信息
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function profile()
    {
        $user = $this->auth->getUser();
        $nickname = $this->request->post('nickname');
        $avatar = $this->request->post('avatar', '', 'trim,strip_tags,htmlspecialchars');
        if ($nickname) {
            $exists = \app\common\model\User::where('nickname', $nickname)->where('id', '<>', $this->auth->id)->find();
            if ($exists) {
                $this->error(__('Nickname already exists'));
            }
            $user->nickname = $nickname;
        }

        $user->avatar = $avatar;
        $user->save();
        $this->success('更新成功');
    }

    /**
     * 修改邮箱
     *
     * @ApiMethod (POST)
     * @param string $email 邮箱
     * @param string $captcha 验证码
     */
    public function changeemail()
    {
        $user = $this->auth->getUser();
        $email = $this->request->post('email');
        $captcha = $this->request->post('captcha');
        if (!$email || !$captcha) {
            $this->error(__('Invalid parameters'));
        }
        if (!Validate::is($email, "email")) {
            $this->error(__('Email is incorrect'));
        }
        if (\app\common\model\User::where('email', $email)->where('id', '<>', $user->id)->find()) {
            $this->error(__('Email already exists'));
        }
        $result = Ems::check($email, $captcha, 'changeemail');
        if (!$result) {
            $this->error(__('Captcha is incorrect'));
        }
        $verification = $user->verification;
        $verification->email = 1;
        $user->verification = $verification;
        $user->email = $email;
        $user->save();

        Ems::flush($email, 'changeemail');
        $this->success();
    }

    /**
     * 修改手机号
     *
     * @ApiMethod (POST)
     * @param string $mobile 手机号
     * @param string $captcha 验证码
     */
    public function changemobile()
    {
        $user = $this->auth->getUser();
        $mobile = $this->request->post('mobile');
        $captcha = $this->request->post('captcha');
        if (!$mobile || !$captcha) {
            $this->error(__('Invalid parameters'));
        }
        if (!Validate::regex($mobile, "^1\d{10}$")) {
            $this->error(__('Mobile is incorrect'));
        }
        if (\app\common\model\User::where('mobile', $mobile)->where('id', '<>', $user->id)->find()) {
            $this->error(__('Mobile already exists'));
        }
        $result = Sms::check($mobile, $captcha, 'changemobile');
        if (!$result) {
            $this->error(__('Captcha is incorrect'));
        }
        $verification = $user->verification;
        $verification->mobile = 1;
        $user->verification = $verification;
        $user->mobile = $mobile;
        $user->save();

        Sms::flush($mobile, 'changemobile');
        $this->success();
    }

    /**
     * 第三方登录
     *
     * @ApiMethod (POST)
     * @param string $platform 平台名称
     * @param string $code Code码
     */
    public function third()
    {
        $url = url('user/index');
        $platform = $this->request->post("platform");
        $code = $this->request->post("code");
        $config = get_addon_config('third');
        if (!$config || !isset($config[$platform])) {
            $this->error(__('Invalid parameters'));
        }
        $app = new \addons\third\library\Application($config);
        //通过code换access_token和绑定会员
        $result = $app->{$platform}->getUserInfo(['code' => $code]);
        if ($result) {
            $loginret = \addons\third\library\Service::connect($platform, $result);
            if ($loginret) {
                $data = [
                    'userinfo' => $this->auth->getUserinfo(),
                    'thirdinfo' => $result
                ];
                $this->success(__('Logged in successful'), $data);
            }
        }
        $this->error(__('Operation failed'), $url);
    }

    /**
     * 重置密码
     *
     * @ApiMethod (POST)
     * @param string $mobile 手机号
     * @param string $newpassword 新密码
     * @param string $captcha 验证码
     */
    public function resetpwd()
    {
        $type = $this->request->post("type", "mobile");
        $mobile = $this->request->post("mobile");
        $email = $this->request->post("email");
        $newpassword = $this->request->post("newpassword");
        $captcha = $this->request->post("captcha");
        if (!$newpassword || !$captcha) {
            $this->error(__('Invalid parameters'));
        }
        //验证Token
        if (!Validate::make()->check(['newpassword' => $newpassword], ['newpassword' => 'require|regex:\S{6,30}'])) {
            $this->error(__('Password must be 6 to 30 characters'));
        }
        if ($type == 'mobile') {
            if (!Validate::regex($mobile, "^1\d{10}$")) {
                $this->error(__('Mobile is incorrect'));
            }
            $user = \app\common\model\User::getByMobile($mobile);
            if (!$user) {
                $this->error(__('User not found'));
            }
            $ret = Sms::check($mobile, $captcha, 'resetpwd');
            if (!$ret) {
                $this->error(__('Captcha is incorrect'));
            }
            Sms::flush($mobile, 'resetpwd');
        } else {
            if (!Validate::is($email, "email")) {
                $this->error(__('Email is incorrect'));
            }
            $user = \app\common\model\User::getByEmail($email);
            if (!$user) {
                $this->error(__('User not found'));
            }
            $ret = Ems::check($email, $captcha, 'resetpwd');
            if (!$ret) {
                $this->error(__('Captcha is incorrect'));
            }
            Ems::flush($email, 'resetpwd');
        }
        //模拟一次登录
        $this->auth->direct($user->id);
        $ret = $this->auth->changepwd($newpassword, '', true);
        if ($ret) {
            $this->success(__('Reset password successful'));
        } else {
            $this->error($this->auth->getError());
        }
    }

    /**
     * 重置安全密码
     */
    public function resetpwd2()
    {
        $type = $this->request->post("type", "mobile");
        $mobile = $this->request->post("mobile");
        $email = $this->request->post("email");
        $newpassword = $this->request->post("newpassword");
        $captcha = $this->request->post("captcha");
        if (!$newpassword || !$captcha) {
            $this->error(__('Invalid parameters'));
        }
        //验证Token
        if (!Validate::make()->check(['newpassword' => $newpassword], ['newpassword' => 'require|regex:\S{6,30}'])) {
            $this->error(__('Password must be 6 to 30 characters'));
        }
        if ($type == 'mobile') {
            if (!Validate::regex($mobile, "^1\d{10}$")) {
                $this->error(__('Mobile is incorrect'));
            }
            $user = \app\common\model\User::getByMobile($mobile);
            if (!$user) {
                $this->error(__('User not found'));
            }
            $ret = Sms::check($mobile, $captcha, 'resetpwd');
            if (!$ret) {
                $this->error(__('Captcha is incorrect'));
            }
            Sms::flush($mobile, 'resetpwd');
        } else {
            if (!Validate::is($email, "email")) {
                $this->error(__('Email is incorrect'));
            }
            $user = \app\common\model\User::getByEmail($email);
            if (!$user) {
                $this->error(__('User not found'));
            }
            $ret = Ems::check($email, $captcha, 'resetpwd');
            if (!$ret) {
                $this->error(__('Captcha is incorrect'));
            }
            Ems::flush($email, 'resetpwd');
        }
        $newpassword = $this->auth->getEncryptPassword($newpassword, $user->salt);
        $ret = $user->save(['password' => $newpassword]);;
        if ($ret) {
            $this->success(__('Reset password successful'));
        } else {
            $this->error($this->auth->getError());
        }
    }

    /**
     * 修改登录密码
     */
    public function changepwd()
    {
        $oldpassword = $this->request->post("oldpassword");
        $newpassword = $this->request->post("newpassword");
        if (!$newpassword || !$oldpassword) {
            $this->error(__('Invalid parameters'));
        }

        $ret = $this->auth->changepwd($newpassword, $oldpassword);
        if ($ret) {
            $this->success(__('Reset password successful'));
        } else {
            $this->error($this->auth->getError());
        }
    }

    /**
     * 我的团队
     * @throws \think\Exception
     * @throws \think\exception\DbException
     */
    public function myTeam()
    {
        $user = $this->auth->getUser();

        if ($user->is_leader != 1 && $user->is_manager != 1) {
            $this->error('非法操作！');
        }

        $userId = $user->id;
        $pageSize = $this->request->post('page_size', 15);
//        $username = $this->request->post('username');

        $where = [
            'id' => ['<>', $userId]
        ];

        if ($user->is_manager == 1) {
            $department_ids = Lists::where('status', 'normal')->where('is_achievement', 1)->column('id');
            $where['department_id'] = ['in', $department_ids];
        } else if ($user->is_leader == 1) {
            $where['department_id'] = $user->department_id;
        }

//        if ($username) {
//            $where['username'] = ['like', '%' . $username . '%'];
//        }
//var_dump($where);die;
        $lists = \app\admin\model\department\User::field('id,username,avatar,status,mobile')->where($where)->order('id asc')->paginate($pageSize);

        $this->success('数据为', $lists);
    }

    /**
     * 收支记录
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function profile_cost()
    {
        $user = $this->auth->getUser();
        if ($user->is_super == 1) {
            $this->error('非法操作！');
        }
        $month = date('Y-m', time());
        $date = $this->request->post('date', $month);
        $time = strtotime($date);
        $userId = $this->auth->getUser()->id;

        $cinfo = Cost::where('user_id', $userId)->where('date', $time)->find();
        if (!$cinfo) {
            $this->error('该月份无收支记录！');
        }

        $this->success('收支记录', $cinfo);
    }

    /**
     * 上传凭证
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function change_profile_cost()
    {
        $id = $this->request->post('id');
        $image = $this->request->post('image');
        if (!$id || !$image) {
            $this->error('参数缺失！');
        }
        $row = Cost::find($id);

        if ($row->status != 0) {
            $this->error('不可上传凭证！');
        }

        $row->image = $image;
        $row->status = 1;
        $res = $row->save();

        if (!$res) {
            $this->error('上传失败！');
        }

        $this->success('上传成功！');
    }

    /**
     * 部门统计
     */
    public function statistics()
    {
        $user = $this->auth->getUser();
        if ($user->is_leader != 1 && $user->is_manager != 1) {
            $this->error('非法操作！');
        }

        $day = date('Y-m-d', time());
        $date = $this->request->post('date', $day);

        if ($user->is_leader == 1) {
            $map = [
                'status' => 'normal'
            ];
            $map['department_id'] = $user->department_id;
            $user_ids = \app\admin\model\department\User::where($map)->column('id');
        } else {
            $user_ids = [];
        }

        $where1 = [
            'status' => 20,
        ];

        if ($user_ids) {
            $where1['department_user_id'] = ['in', $user_ids];
        }

        $start_time = strtotime($date);
        $end_time = $start_time + 24 * 60 * 60;
        $where1['finish_time'] = [['>=', $start_time], ['<', $end_time]];

        $num1 = $num2 = 0;
        $total1 = $total2 = 0.00;
        $money1 = $money2 = 0.00;
        $lists1 = Order::field('id,total,rate')
            ->where($where1)
            ->order('id asc')
            ->select();

        if ($lists1) {
            foreach ($lists1 as $val) {
                $num1 += 1;
                $total1 += $val->total;
                $money1 += round($val->total * $val->rate * 0.01, 2);
            }
        }

        $where2 = [
            'updatetime' => [['>=', $start_time], ['<', $end_time]],
            'backinfo' => 'fail',
        ];

        if ($user_ids) {
            $where2['department_user_id'] = ['in', $user_ids];
        }

        $lists2 = Order::field('id,total,rate,transfee')
            ->where($where2)
            ->order('id asc')
            ->select();

        if ($lists2) {
            foreach ($lists2 as $val) {
                $num2 += 1;
                $total2 += $val->total;
                $money2 += round($val->transfee, 2);
            }
        }

        $this->success('财务统计', ['num1' => $num1, 'total1' => $total1, 'money1' => round($money1, 2), 'num2' => $num2, 'total2' => $total2, 'money2' => $money2]);
    }

    /**
     * 盈利排名和工作量排名统计
     */
    public function ranks()
    {
        $date_type = $this->request->post('date_type', 1);
        $rank_type = $this->request->post('rank_type', 1);

        $money1 = $money2 = 0.00;
        $rank1 = $rank2 = 0;

        switch ($date_type) {
            case 1:
                $start = strtotime('today');
                break;
            case 2:
                $start = strtotime('Sunday -6 day', time());
                break;
        }

        $user_id = $this->auth->id;
        $user = \app\admin\model\department\User::find($user_id);
        if ($rank_type == 1) {
            $where = [
                'status' => 20,
                'department_user_id' => $user_id,
                'updatetime' => ['>=', $start]
            ];

            $where_str = ' status = 20 and updatetime >= ' . $start;
            // 个人盈利
            $orders_sql = "select department_user_id,sum(profile) as stotal from fa_product_order where " . $where_str . " group by department_user_id order by stotal desc";
            $orders = Db::query($orders_sql);
            if ($orders) {
                foreach ($orders as $key => $val) {
                    if ($val['department_user_id'] == $user_id) {
                        $money1 = $val['stotal'];
                        $rank1 = $key + 1;
                    }
                }
            }

            // 团队盈利
            $dlists = Lists::where('status', 'normal')->select();
            $team_data = [];
            foreach ($dlists as $v1) {
                $ids = \app\admin\model\department\User::where('department_id', $v1->id)->column('id');
                if ($ids) {
                    unset($where['department_user_id']);
                    $where['department_user_id'] = ['in', $ids];
                    $total = Order::where($where)->sum('profile');
                } else {
                    $total = 0.00;
                }

                $item = [
                    'id' => $v1->id,
                    'total' => $total
                ];

                $team_data[] = $item;
            }

            $total_arr = array_column($team_data, 'total');
            array_multisort($total_arr, SORT_DESC, $team_data);
            foreach ($team_data as $k2 => $v2) {
                if ($v2['id'] == $user->department_id) {
                    $money2 = $v2['total'];
                    $rank2 = $k2 + 1;
                }
            }
        } elseif ($rank_type == 2) {
            $where_str = ' datetime >= ' . $start;
            $loads_sql = "select user_id,sum(num1) as snum1,sum(num2) as snum2 from fa_workload where " . $where_str . " group by user_id";
            $loads = Db::query($loads_sql);
            $loads_data = [];
            if ($loads) {
                foreach ($loads as $key => $val) {
                    $item = [
                        'id' => $val['user_id'],
                        'num' => (int)($val['snum1'] + $val['snum2'])
                    ];

                    $loads_data[] = $item;
                }
            }

            $num_arr = array_column($loads_data, 'num');
            array_multisort($num_arr, SORT_DESC, $loads_data);
            foreach ($loads_data as $k3 => $v3) {
                if ($v3['id'] == $user_id) {
                    $money1 = (int)$v3['num'];
                    $rank1 = $k3 + 1;
                }
            }
        }

        $this->success('排名统计', ['money1' => $money1, 'rank1' => $rank1, 'money2' => $money2, 'rank2' => $rank2]);
    }

    /**
     * 设备登记
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function addDevice()
    {
        $clientId = $this->request->get('client_id');
        if (!$clientId) {
            $this->error('参数缺失！');
        }

        $userId = $this->auth->id;
        Info::where('user_id', $userId)->delete();
        Info::create([
            'device_id' => $clientId,
            'user_id' => $userId
        ]);
        $this->success('该设备登记成功！');
    }
}
